package online_store.model.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import online_store.entity.ProductEntity;

@Repository
public class ProductDao {

	@PersistenceContext(name="online_store-persistence")
	EntityManager em;
	
	public void createProduct(ProductEntity product){
		em.persist(product);
	}
	
	public List<ProductEntity> findAll(){
		List<ProductEntity> list = new ArrayList<ProductEntity>();
		
		Query query = em.createQuery("SELECT product FROM ProductEntity product");
		if(!query.getResultList().isEmpty()){
			list = (List<ProductEntity>) query.getResultList();
		}
		
		return list;
	}
	
	public ProductEntity getProduct(int productId){
		ProductEntity product = null;
		
		Query query = em.createQuery("SELECT product FROM ProductEntity product WHERE product.product_id=:product_id");
		query.setParameter("product_id", productId);
		if(!query.getResultList().isEmpty()){
			product = new ProductEntity();
			product = (ProductEntity) query.getSingleResult();
		}

		return product;
	}
	
	public ProductEntity findByName(String name){
		ProductEntity product = null;
		
		Query query = em.createQuery("SELECT product FROM ProductEntity product WHERE product.name=:name");
		query.setParameter("name", name);
		if(!query.getResultList().isEmpty()){
			product = new ProductEntity();
			product = (ProductEntity) query.getSingleResult();
		}

		return product;
	}
	
	public void updateProduct(ProductEntity product){
		em.merge(product);
	}
	
	public void deleteProduct(int productId){
		ProductEntity product = em.find(ProductEntity.class, productId);
		em.remove(product);
	}
}
